package com.lunago.agent.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.lunago.agent.constant.ServiceCode;
import com.lunago.agent.ex.ServiceException;
import com.lunago.agent.mapper.OrderGemsLevelMapper;
import com.lunago.agent.mapper.PermiumOrderMapper;
import com.lunago.agent.mapper.UserGemsMapper;
import com.lunago.agent.mapper.UserPermiumMapper;
import com.lunago.agent.pojo.dto.PayResultVO;
import com.lunago.agent.pojo.entity.*;
import com.lunago.agent.properties.PayPalProperties;
import com.lunago.agent.service.PaymentService;
import com.lunago.agent.service.UserGemsService;
import com.lunago.agent.service.UserPermiumService;
import com.paypal.core.PayPalEnvironment;
import com.paypal.core.PayPalHttpClient;
import com.paypal.http.HttpResponse;
import com.paypal.orders.Order;
import com.paypal.orders.OrdersGetRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ton.java.cell.Cell;
import org.ton.java.cell.CellBuilder;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private OrderGemsLevelMapper orderGemsLevelMapper;
    @Autowired
    private PermiumOrderMapper permiumOrderMapper;
    @Autowired
    private UserGemsService userGemsService;
    @Autowired
    private UserPermiumService userPermiumService;;

    private final PayPalProperties payPalProperties;


    @Override
    public List<OrderGemsLevel> queryAllPremiumLevels() {
        return orderGemsLevelMapper.selectByExample(new OrderGemsLevelExample());
    }

    @Override
    public OrderGemsLevel queryPremiumLevelsById(Integer id) {
        return orderGemsLevelMapper.selectByPrimaryKey(id);
    }

    @Override
    public String getPayLoad(String orderId) {
        Cell cell = CellBuilder.beginCell().storeUint(0, 32).storeString(orderId).endCell();
        String base64 = cell.toBase64();
        return base64;
    }

    @Override
    public void submitOrder(PermiumOrder order) {
        order.setOrderTime(new Date());
        order.setStatus(0);
        permiumOrderMapper.insert(order);
    }

    @Override
    public PermiumOrder queryPermiumOrderByOrderId(String orderId) {
        PermiumOrderExample example = new PermiumOrderExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        List<PermiumOrder> list = permiumOrderMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void updatePermiumOrderStatus(String orderId, int status) {
        PermiumOrderExample example = new PermiumOrderExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        PermiumOrder permiumOrder = new PermiumOrder();
        permiumOrder.setStatus(status);
        permiumOrderMapper.updateByExampleSelective(permiumOrder, example);
    }

    @Override
    public void updateUserGems(Long userId, Integer permiumLevelId) {
        OrderGemsLevel orderGemsLevel = queryPremiumLevelsById(permiumLevelId);
        Integer isPermium = orderGemsLevel.getIsPermiumLevel();
        Integer gems = orderGemsLevel.getGems();
        // 更新用户积分
        UserGems userGems = userGemsService.queryMyGems(userId);
        if (userGems != null) {
            // 修改用户点数
            Integer userGemsGems = userGems.getGems();
            userGemsGems += gems;
            userGems.setGems(userGemsGems);
            userGemsService.updateUserGems(userGems);
            if  (isPermium == 1) {
                // 修改用户会员状态
                userPermiumService.updateUserPermiumStatus(userId, 1);
            }
        } else {
            throw new ServiceException(ServiceCode.ERROR_UNKNOWN, "未查到用户信息");
        }
    }

    private PayPalHttpClient getPayPalClient() {
        PayPalEnvironment environment = new PayPalEnvironment.Live(payPalProperties.getClientId(),
                payPalProperties.getClientSecret());
        return new PayPalHttpClient(environment);
    }
    @Override
    public PayResultVO getOrder(String token) {
        PayResultVO payResultVO = new PayResultVO();
        payResultVO.setStatus(0);
        PayPalHttpClient payPalClient = this.getPayPalClient();
        OrdersGetRequest getOrderRequest = new OrdersGetRequest(token);
        HttpResponse<Order> getOrderResult = null;
        try {
            getOrderResult = payPalClient.execute(getOrderRequest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Order order = getOrderResult.result();
        if (ObjectUtil.isNotNull(order)) {
            String status = order.status();
            if ("COMPLETED".equals(status)) {
                payResultVO.setStatus(1);
                payResultVO.setStatusDesc("支付成功");
                payResultVO.setSuccessTime(LocalDateTimeUtil.parse(order.updateTime(), DatePattern.UTC_PATTERN));
            } else {
                payResultVO.setStatus(0);
                payResultVO.setStatusDesc(status);
            }
        }
        return payResultVO;
    }

    public PaymentServiceImpl(PayPalProperties payPalProperties) {
        this.payPalProperties = payPalProperties;
    }
}













